package com.yami.shop.app.controller;

import com.yami.shop.app.config.PushMessageUtil;
import com.yami.shop.app.utils.HttpResult;
import com.yami.shop.common.bean.Qiniu;
import com.yami.shop.service.AttachFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件上传 controller
 *
 */
@RestController
@RequestMapping("/app/file")
public class FileController {

    @Autowired
    private AttachFileService attachFileService;
    @Autowired
    private Qiniu qiniu;

    @PostMapping("/upload/element")
    public ResponseEntity<String> uploadElementFile(@RequestParam("file") MultipartFile file) throws IOException {
        if(file.isEmpty()){
            return ResponseEntity.noContent().build();
        }
        // 上传并返回新文件名称
        String fileName = attachFileService.upload(file);
        return ResponseEntity.ok(fileName);
    }

    @PostMapping("/upload/tinymceEditor")
    public ResponseEntity<String> uploadTinymceEditorImages(@RequestParam("editorFile") MultipartFile file) throws IOException{
        // 上传并返回新文件名称
        String fileName = attachFileService.upload(file);
        return ResponseEntity.ok(qiniu.getResourcesUrl() + fileName);
    }

    @PostMapping("/ScanUpload")
    public HttpResult ScanUpload(@RequestParam("file") MultipartFile file, @RequestParam("cid")String cid) throws IOException{
        if(file.isEmpty()){
            return HttpResult.failure("文件为空!");
        }
        String fileName = attachFileService.ScanUpload(file.getBytes(),file.getOriginalFilename(),cid);
        return HttpResult.success(fileName);
    }

    /**
     * 获取当前cid下最近上传的一张图片
     */
    @PostMapping("/getLatestPicByCid")
    public HttpResult getLatestPicByCid(String cid){
        String  photoUrl =   attachFileService.getLatestPicByCid(cid);
        try {
            PushMessageUtil.pushToSingleByCid(cid,"上传成功!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return  HttpResult.success(photoUrl);
    }

}
